package jp.co.lab3;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class Utils {
	public static String getContents(Context context, long date, String def) {
		DatabaseHelper helper = null;
		SQLiteDatabase db = null;
		Cursor cur = null;
		try {
			helper = new DatabaseHelper(context);
			db = helper.getWritableDatabase();
			cur = db.query(DatabaseHelper.TABLE_DIARY, 
					new String[] { DatabaseHelper.FIELD_CONTENTS },
					DatabaseHelper.FIELD_DATE + " = ?",
					new String[] { Long.toString(date) }, null, null, null, "1");
			if (cur != null && cur.moveToFirst()) {
				String contents = cur.getString(cur.getColumnIndex(DatabaseHelper.FIELD_CONTENTS));
				return contents;
			} else {
				return def;
			}
		} finally {
			if (cur != null) {
				cur.close();
			}
			if (db != null) {
				db.close();
			}
			if (helper != null) {
				helper.close();
			}
		}
	}
	
	public static void updateContents(Context context, long date, String contents) {
		DatabaseHelper helper = null;
		SQLiteDatabase db = null;
		try {
			helper = new DatabaseHelper(context);
			db = helper.getWritableDatabase();
			ContentValues values = new ContentValues();
			values.put(DatabaseHelper.FIELD_CONTENTS, contents);
			db.update(DatabaseHelper.TABLE_DIARY, values, 
					DatabaseHelper.FIELD_DATE + " = ?",
					new String[] { Long.toString(date) });
		} finally {
			if (db != null) {
				db.close();
			}
			if (helper != null) {
				helper.close();
			}
		}
	}
	
	public static void createContents(Context context, long date, String contents) {
		DatabaseHelper helper = null;
		SQLiteDatabase db = null;
		try {
			helper = new DatabaseHelper(context);
			db = helper.getWritableDatabase();
			ContentValues values = new ContentValues();
			values.put(DatabaseHelper.FIELD_DATE, date);
			values.put(DatabaseHelper.FIELD_CONTENTS, contents);
			db.insert(DatabaseHelper.TABLE_DIARY, null, values);
		} finally {
			if (db != null) {
				db.close();
			}
			if (helper != null) {
				helper.close();
			}			
		} 
	}
}
